//
//  DFProductsProductDetailControllerViewController.m
//  cf
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 xuzenghui. All rights reserved.
//

#import "DFProductsProductDetailController.h"
#import "DFProductsProductDetailModel.h"
#import "UIImageView+WebCache.h"
#import "PKRequestManager.h"
#import "DFProductsProductDetailCell.h"
#import "DFProductsProductDataDetailController.h"
#import "DFProductsProductAtlasController.h"
#import "FMDatabase.h"
#import "UMSocial.h"
#import "Reachability.h"
#import "RTSpinKitView.h"
@interface DFProductsProductDetailController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic,strong)DFProductsProductDetailModel *model;
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,strong)UIView *pickView;
@property (nonatomic,strong)UIView *headerView;
@property (nonatomic,strong)DFProductsProductDataDetailController *detailDataController;
@property (nonatomic,strong)DFProductsProductAtlasController *atlasController;
@property (nonatomic,strong)NSMutableArray *collectionArr;
@property (nonatomic,strong)UIButton *collection;
@property (nonatomic,strong)FMDatabase *dataBase;  //  数据库存储
@property (nonatomic,strong)UIAlertController *alertCS; //  收藏成功
@property (nonatomic,strong)UIAlertController *alertNCS; //  取消收藏

@end

@implementation DFProductsProductDetailController


- (void)addCollectionBtnAndShareBtn
{
    _collection = [UIButton buttonWithType:UIButtonTypeCustom];
    _collection.frame = CGRectMake(kScreenWidth - 100, 9, 26, 26);
    [_collection setImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
    [_collection addTarget:self action:@selector(didClickToCollection:) forControlEvents:UIControlEventTouchUpInside];
    [_collection setImage:[UIImage imageNamed:@"iconfont-shoucang (1)"] forState:UIControlStateSelected];
    [self.topView addSubview:_collection];

//  判断是否收藏
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"DFront.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    if ([_dataBase open]) {
        NSLog(@"打开成功");
    }
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from collections"];
    while ([resultSet next]) {
        NSString *proId = [resultSet stringForColumn:@"proId"];
        if (_proId == proId) {
            _collection.selected = YES;
        }
    }
    
    UIButton *share = [UIButton buttonWithType:UIButtonTypeCustom];
    share.frame = CGRectMake(kScreenWidth - 50, 9, 26, 26);
    [share addTarget:self action:@selector(didClickToShare:) forControlEvents:UIControlEventTouchUpInside];
    [share setImage:[UIImage imageNamed:@"iconfont-fenxiang"] forState:UIControlStateNormal];
    [self.topView addSubview:share];

}

//  收藏
- (void)didClickToCollection:(UIButton*)button
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    if ([reach isReachable]) {
     if ([_dataBase open]) {
        [_dataBase executeUpdate:@"create table collections (subcateId text,proId text,name text,price,text)"];
    }else
    {
        NSLog(@"收藏数据库失败");
    }
    if (button.selected == NO) {
        if (_model.proInfo.name.length != 0) {
             [_dataBase executeUpdate:@"insert into collections (subcateId, proId, name, price) values (?,?,?,?)",_subcateId , _proId , _model.proInfo.name ,_model.proInfo.price];
             _alertCS = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:_alertCS animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(alertControllerDismiss) userInfo:nil repeats:NO];
        button.selected = YES;
        }
    }
    else{
        _alertNCS = [UIAlertController alertControllerWithTitle:@"提示" message:@"已取消收藏" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:_alertNCS animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(alertControllerDismiss) userInfo:nil repeats:NO];
        [_dataBase executeUpdate:@"delete from collections where proId = ?",_proId];
        button.selected = NO;
    }
}
    else
    {
        _alertCS = [UIAlertController alertControllerWithTitle:@"提示" message:@"请联网后重试" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:_alertCS animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(alertControllerDismiss) userInfo:nil repeats:NO];
    }
}
- (void)alertControllerDismiss
{
    [_alertCS dismissViewControllerAnimated:YES completion:nil];
    [_alertNCS dismissViewControllerAnimated:YES completion:nil];
}

//  社会化分享
- (void)didClickToShare:(UIButton*)button
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56342e7467e58e0448004498"
                                      shareText:_model.proInfo.name
                                     shareImage:[UIImage imageNamed:@"-text"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:nil];
}
- (void)addPickView
{
    _pickView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, 40)];
    UIButton *summarizeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    summarizeBtn.frame = CGRectMake(10, 10, 40, 20);
    summarizeBtn.tag = 1000 + 0;
    [summarizeBtn setTitleColor:[UIColor colorWithRed:1.000 green:0.173 blue:0.176 alpha:1.000] forState:UIControlStateNormal];
    [summarizeBtn setTitle:@"综述" forState:UIControlStateNormal];
    [summarizeBtn addTarget:self action:@selector(pickView:)
           forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *detailBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    detailBtn.frame = CGRectMake(kScreenWidth / 2 - 30, 10, 60, 20);
    detailBtn.tag = 1000 + 1;
    [detailBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [detailBtn setTitle:@"详细参数" forState:UIControlStateNormal];
    [detailBtn addTarget:self action:@selector(pickView:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *picBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    picBtn.frame = CGRectMake(kScreenWidth - 50, 10, 40, 20);
    picBtn.tag = 1000 + 2;
    [picBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [picBtn setTitle:@"图库" forState:UIControlStateNormal];
    [picBtn addTarget:self action:@selector(pickView:) forControlEvents:UIControlEventTouchUpInside];

    [_pickView addSubview:summarizeBtn];
    [_pickView addSubview:detailBtn];
    [_pickView addSubview:picBtn];
    
    UILabel *lineLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 39, kScreenWidth, 1)];
    lineLab.backgroundColor = [UIColor redColor];
    [_pickView addSubview:lineLab];
    
    [self.view addSubview:_pickView];
}
//  综述，详参，图库切换
- (void)pickView:(UIButton*)button
{
    self.scrollView.contentOffset = CGPointMake((button.tag - 1000)*kScreenWidth , -20);
    [button setTitleColor:[UIColor colorWithRed:1.000 green:0.155 blue:0.067 alpha:1.000] forState:UIControlStateNormal];
    for (int i = 0; i < 3 ; i++) {
        if (i != button.tag - 1000) {
            [(UIButton*)(_pickView.subviews[i]) setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
}
//  商品展示（tableview 表头）
- (void)addHeaderView
{
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 3 / 4 + 70 + [self heightOfString:_model.proInfo.brief])];
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 3 / 4)];
    
    UILabel *nameLab = [[UILabel alloc]initWithFrame:CGRectMake(10, kScreenWidth * 3 / 4, kScreenWidth - 20, 40)];
    nameLab.font = [UIFont systemFontOfSize:18 weight:0.5];
    nameLab.numberOfLines = 0;
    
    UILabel *detailLab = [[UILabel alloc]initWithFrame:CGRectMake(10, kScreenWidth * 3 / 4 + 40, kScreenWidth - 30, 0)];
    detailLab.font = [UIFont systemFontOfSize:15];
    detailLab.numberOfLines = 0;
    
    UILabel *priceLab = [[UILabel alloc]initWithFrame:CGRectMake(20, kScreenWidth * 3 / 4 + 120, 80, 30)];
    priceLab.textColor = [UIColor colorWithRed:1.000 green:0.171 blue:0.131 alpha:1.000];
    [_headerView addSubview:imageview];
    [_headerView addSubview:nameLab];
    [_headerView addSubview:detailLab];
    [_headerView addSubview:priceLab];
    
    self.mainTableView.tableHeaderView = _headerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addCollectionBtnAndShareBtn];
    self.view.backgroundColor = [UIColor whiteColor];
    _collectionArr = [NSMutableArray array];
    // Do any additional setup after loading the view.
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, -20, kScreenWidth, kScreenHeight + 20)];
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(kScreenWidth * 3, kScreenHeight - 84);
//  _scrollView.scrollEnabled = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 104,  kScreenWidth, kScreenHeight - 84) style:UITableViewStyleGrouped];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.mainTableView registerClass:[DFProductsProductDetailCell class] forCellReuseIdentifier:@"cell"];

    [_scrollView addSubview:self.mainTableView];
//  产品详细参数界面
    _detailDataController = [[DFProductsProductDataDetailController alloc]init];
    _detailDataController.proId = _proId;
    _detailDataController.view.frame = CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight) ;
    [_scrollView addSubview:_detailDataController.view];
    
//  产品图片界面
    _atlasController = [[DFProductsProductAtlasController alloc]init];
    
#warning 先传值再调用self.view
    _atlasController.subcateId = _subcateId;
    _atlasController.proId = _proId;
    _atlasController.view.frame = CGRectMake(kScreenWidth * 2, 0, kScreenWidth, kScreenHeight);
    [self addChildViewController:_atlasController];
    [_scrollView addSubview:_atlasController.view];
    
    [self requestData];
    
//  后添加状态栏，选择栏
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.backBtn];
    [self addPickView];
//  用于刷新
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    RTSpinKitView *refreash = [[RTSpinKitView alloc]initWithStyle:RTSpinKitViewStyleWanderingCubes color:[UIColor redColor]];
    refreash.center = CGPointMake(CGRectGetMidX(screenBounds), CGRectGetMidY(screenBounds));
    [self.view addSubview:refreash];
}

- (void)requestData
{
    NSString *urlString = [@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_ProDetail_V2&proId=" stringByAppendingString:_proId];
    [PKRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        [self.view.subviews.lastObject removeFromSuperview];
//  数据用于收藏
        _data = data;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        _model = [[DFProductsProductDetailModel alloc]init];
        [_model setValuesForKeysWithDictionary:dic];
        
        [self addHeaderView];
        
        [((UIImageView*)_headerView.subviews[0]) sd_setImageWithURL:[NSURL URLWithString:_model.proInfo.pic]];
        ((UILabel*)_headerView.subviews[1]).text = _model.proInfo.name;
        ((UILabel*)_headerView.subviews[2]).text = _model.proInfo.brief;
        ((UILabel*)_headerView.subviews[2]).frame = CGRectMake(10, kScreenWidth * 3 / 4 + 40, kScreenWidth - 30, [self heightOfString:_model.proInfo.brief]);
        ((UILabel*)_headerView.subviews[3]).text = [_model.proInfo.mark stringByAppendingString:_model.proInfo.price];
        [self.mainTableView reloadData];
        ((UILabel*)_headerView.subviews[3]).frame = CGRectMake(10, kScreenWidth * 3 / 4 + 40 + [self heightOfString:_model.proInfo.brief], 80, 30);
        
        [self.mainTableView reloadData];
    } error:^(NSError *error) {
        
        NSLog(@"请求失败＝＝%@",error);
    }];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _model.sortParamArr.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DFProductsProductDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell configureDataWithModel:_model.sortParamArr[indexPath.row]];
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    UIButton *button = _pickView.subviews[(int)(scrollView.contentOffset.x / kScreenWidth)];
    [button setTitleColor:[UIColor colorWithRed:1.000 green:0.155 blue:0.067 alpha:1.000] forState:UIControlStateNormal];
    for (int i = 0; i < 3; i++) {
        if (i != (int)(scrollView.contentOffset.x / kScreenWidth)) {
            [(UIButton*)(_pickView.subviews[i]) setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return [DFProductsProductDetailCell heithtOfCell:[_model.sortParamArr[indexPath.row] vale]];
}

- (CGFloat)heightOfString:(NSString*)string
{
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];
    
    CGRect bounds = [string boundingRectWithSize:CGSizeMake(kScreenWidth - 30, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return bounds.size.height;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
